from typing import Any

from aiogram import types
from aiogram_dialog import Dialog, DialogManager, Window
from aiogram_dialog.widgets.kbd import Button, Cancel, Group
from aiogram_dialog.widgets.text import Const
from sqlalchemy.exc import DBAPIError
from sqlalchemy.ext.asyncio import AsyncSession

from app.bot.dialog.dialog_states import LanguageSG
from app.bot.dialog.widgets import LocaleText
from app.bot.services.loggers import logger
from app.database.services.users import change_user_language


async def set_user_language(
    call: types.CallbackQuery, widget: Any, manager: DialogManager
):
    try:
        db_session: AsyncSession = manager.middleware_data.get("db_session")
        user_id: int = call.from_user.id
        lang_code: str = widget.widget_id

        await change_user_language(db_session, user_id, lang_code)
        await call.answer("Language changed")

    except (DBAPIError, Exception) as e:
        await call.answer("Error occured")
        logger.exception(e)

    await manager.done()


language_window = Window(
    LocaleText("select-lang"),
    Group(
        Button(Const("🇺🇸 English"), id="en", on_click=set_user_language),
        Button(Const("🇷🇺 Русский"), id="ru", on_click=set_user_language),
        width=2,
    ),
    Cancel(LocaleText("back-btn")),
    state=LanguageSG.list_of_languages,
)

language_dialog = Dialog(language_window)
